<template>
  <div class="login">
    <!--  -->
    <el-avatar
        src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
      />
    <!--  -->
    <el-form :model="formVal" :rules="rules" ref="ruleFormRef">
    <el-form-item prop="'username">
      <el-input v-model="formVal.username" placeholder="请输入手机号" clearable  />
    </el-form-item>
    <el-form-item prop="'password">
      <el-input type="password" v-model="formVal.password" placeholder="请输入密码" show-password />
    </el-form-item>
    </el-form>
    <!--  -->
    <el-button type="primary" @click="handleGoHome">登录</el-button>
    <div class="register">
      <span @click="handleGoRegister">立即注册</span>
      <span> | </span>
      <span>忘记密码</span></div>
  </div>
</template>

<script>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { login } from '../../api/user'
import { ElMessage } from 'element-plus'
export default {
  name: 'Login',
  setup () {
    const ruleFormRef = ref(null)
    const rules = reactive({
      username: [
        { required: true, message: '手机号不可为空', trigger: 'blur', Pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/ }
      ]
    })

    const router = useRouter()
    const formVal = reactive({ username: '', password: '' })
    // 点击登录按钮 axios 请求; 跳转到首页
    const handleGoHome = async () => {
      console.log(formVal)
      try {
        const res = await login(formVal)
        // console.log(res)
        if (res.errno === 0) {
          localStorage.isLogin = true
          router.push('/')
          ElMessage({
            type: 'success',
            message: '登录成功1111',
            icon: '',
            center: true
          })
          formVal.username = ''
          formVal.password = ''
        // router.push({ name: 'Home' })
        } else {
          ElMessage.error('登陆失败')
        }
      } catch (error) {
        ElMessage.error('请求失败')
      }
    }
    // 点击立即注册 跳转到注册页
    const handleGoRegister = () => {
      router.push('/register')
    }
    return { formVal, handleGoHome, handleGoRegister, ruleFormRef, rules }
  }
}
</script>

<style lang="scss" scoped>
.login {
  position: absolute;
  top: 50%;
  left:0;
  right: 0;
  transform: translateY(-50%);
  margin: 0 .8rem;
  .el-avatar {
    display: block;
    margin: 0 auto .4rem auto;
    width: 0.66rem;
    height: 0.66rem;
  }
  .el-button {
    position: relative;
    top: -.5rem;
    width: 100%;
  }
  .register {
    display: flex;
    justify-content: center;
    position: relative;
    top: -.5rem;
    font-size: .15rem;
  }
}
</style>
